# application/mapper/menu.py
from application.extensions.databases import db
from application.models.system.menu import SysMenu
from typing import List, Dict, Any


class MenuMapper:
    """菜单数据访问层"""

    
    @staticmethod
    def select_menu_list(query_params: Dict[str, Any]) -> List[Dict[str, Any]]:
        """
        查询菜单数据
        
        Args:
            query_params: 验证后的查询参数
                - parent_id: 父菜单ID
                - menu_type: 菜单类型

        Returns:
            List[Dict[str, Any]]: 菜单列表数据
        """
        try:
            # 构建查询
            query = db.session.query(SysMenu)
            
            # 添加查询条件
            if 'parent_id' in query_params:
                query = query.filter(SysMenu.parent_id == query_params['parent_id'])
            if 'menu_type' in query_params:
                query = query.filter(SysMenu.menu_type == query_params['menu_type'])
            
            # 执行查询并排序
            menus = query.order_by(SysMenu.order_num).all()

            # 转换为字典列表格式
            menu_list = []
            for menu in menus:
                menu_dict = {
                    "menuId": menu.menu_id,
                    "menuName": menu.menu_name,
                    "parentId": menu.parent_id,
                    "orderNum": menu.order_num,
                    "path": menu.path,
                    "component": menu.component,
                    "queryParam": menu.query_param,
                    "isFrame": str(menu.is_frame) if menu.is_frame is not None else "1",
                    "isCache": str(menu.is_cache) if menu.is_cache is not None else "0",
                    "menuType": menu.menu_type,
                    "visible": menu.visible,
                    "status": menu.status,
                    "perms": menu.perms,
                    "icon": menu.icon,
                    "createDept": menu.create_dept,
                    "remark": menu.remark,
                    "createTime": menu.create_time.strftime("%Y-%m-%d %H:%M:%S") if menu.create_time else None,
                }
                menu_list.append(menu_dict)
            
            return menu_list
            
        except Exception as e:
            from application.extensions.logging import database_logger
            database_logger.error(f"查询菜单列表失败: {e}")
            raise e
